package hc.bre.rest.admin

import hc.bre.cmn.ILoad
import hc.bre.cmn.ListOption
import hc.bre.rest.cmn.SpringContext

@groovy.transform.CompileStatic
@groovy.transform.ToString(includeNames=true,includePackage=false)
class BreAdminConfig{
	ScriptFileMode scriptFileMode = ScriptFileMode.justSelf;
	List<RemoteServer> remoteList;
	List<ProjectEntry> projectList;
	
	int rolemaxid;
	List<BreRole> roleList;
	int usermaxid;
	List<BreUser> userList;
	int version;
	
	static BreAdminConfig getConfig()
	{
		BreAdminService adminService = SpringContext.applicationContext.getBean(BreAdminService);
		adminService.getConfig();
	}
	
	static BreAdminConfig create() {
		BreAdminConfig adminConfig = new BreAdminConfig();
		
		adminConfig.scriptFileMode = ScriptFileMode.justSelf;
		adminConfig.remoteList =[];
		adminConfig.projectList = [];
		
		BreRole role  = new BreRole(
				id:++adminConfig.rolemaxid,
				code:'Administrators',
				name:'Administrators',
				perms :(Set<String>)["*:*"]);

		BreUser user = new BreUser(id:++adminConfig.usermaxid,
		code:'admin',
		name:'admin',
		salt:'my wechat id:sleepywang,my email:sleepwang@qq.com',
		password:'aA881bLwMhst6AmfBEkcJYu67VCrkbn1eIz3YyVZKdQ=');
		//password:999999
	
		user.perms = (Set<String>)['*:*:*','@func:*']
		user.roleIds.add(role.id);

		adminConfig.roleList =[];
		adminConfig.roleList.add(role);
		adminConfig.userList =[];
		adminConfig.userList.add(user);
		
//		role  = new BreRole(
//			id:++sec.rolemaxid,
//			code:'RunAnythings',
//			name:'RunAnythings',
//			perms :(Set<String>)["*:"+BrePermission.run]);
//		sec.roleList.add(role);

		return adminConfig;
	}

	public BreAdminConfig load(Map<Object, Object> map) {
		scriptFileMode = ScriptFileMode.parse(map.scriptFileMode)
		remoteList = hc.Util.loadList(map['remoteList'], RemoteServer)
		projectList = hc.Util.loadList(map['projectList'], ProjectEntry)
		
		usermaxid = map['usermaxid'] as Integer
		rolemaxid = map['rolemaxid'] as Integer
		version = map['version'] as Integer
		
		roleList = hc.Util.loadList(map['roleList'], BreRole)
		userList = hc.Util.loadList(map['userList'], BreUser)

		userList.each { user ->
			user.perms=(Set<String>)[];
			user.roleIds.each { roleId ->
				BreRole role = roleList.find {roleId == it.id};
				if(role) {
					user.perms.addAll(role.perms);
				};
			};
		};
		

		return this;
	}
}
